<?php
// 应用公共文件

// 页面类型的枚举
const pageType = [
    'default' => [
        'name' => 'default',
        'value' => 1
    ],
    'product' => [
        'name' => 'product',
        'value' => 2
    ],
    'cases' => [
        'name' => 'cases',
        'value' => 3
    ],
];

function p(array $arr): void
{
    echo '<pre>';
    print_r($arr);
    echo '</pre>';
}

/**
 * @description
 * @param array $arr 二维数组
 * @param string $pk 主键id
 * @param string $upid 表示父级id的字段
 * @param string $child 子目录的键
 * @return array
 */
function getTree(array $arr = array(), string $pk = 'id', string $upid = 'parent_id', string $child = 'children'): array
{
    $items = array();
    foreach ($arr as $val) {
        $items[$val[$pk]] = $val;
    }
    $tree = array();
    foreach ($items as $k => $val) {
        if (isset($items[$val[$upid]])) {
            $items[$val[$upid]][$child][] =& $items[$k];

        } else {
            $tree[] = &$items[$k];
        }
    }

    return $tree;
}

/**
 * subject content
 *
 * @param array $tree
 * @return array
 * @author justary  <justary@126.com>
 * @date 2024-06-28 13:38
 */
function formatTree(array $tree = []): array
{
    foreach ($tree as $item => $value) {

        if (!isset($value['children'])) {
            $tree[$item]['children'] = [];
            $tree[$item]['isParent'] = false;
        } else {
            $tree[$item]['isParent'] = true;
            foreach ($value['children'] as $k => $v) {

                if (!isset($v['children'])) {

                    $tree[$item]['children'][$k]['children'] = [];

                    $tree[$item]['children'][$k]['isParent'] = false;

                } else {

                    $tree[$item]['children'][$k]['isParent'] = true;
                    foreach ($v['children'] as $kk => $vv) {

                        if (!isset($vv['children'])) {

                            $tree[$item]['children'][$k]['children'][$kk]['children'] = [];

                            $tree[$item]['children'][$k]['children'][$kk]['isParent'] = false;
                        }
                    }
                }
            }
        }

    }


    return $tree;
}

/**
 * 参数生成
 * @param $params array 数组参数
 * @return string
 */
function paramsBuilder($params)
{
    return '/' . implode('/', $params);
}

/**
 * 无限提取数组中的某个字段
 * @param $array array 目标数组
 * @param $field string 要提取的字段
 * @return array
 */
function unlimitedFindItems($array, $field): array
{
    $items = [];
    foreach ($array as $key => $value) {
        if ($key === $field && is_array($value) && $value) {
            $items = array_merge($items, $value);
        } elseif (is_array($value)) {
            $foundInSubArray = unlimitedFindItems($value, $field);
            $items = array_merge($items, $foundInSubArray);
        }
    }
    return $items;
}

/**
 * 提取数组里最后一个children数组
 * @param $arrays
 * @return array
 */
function extractChildrenFromLastDimension($arrays)
{
    $childrenArrays = [];
    foreach ($arrays as $array) {
        $lastDimension = end($array);
        if (isset($lastDimension['children'])) {
            $childrenArrays[] = $lastDimension['children'];
        }
    }
    return $childrenArrays;
}

/**
 * 远程翻译
 * @param $keywords
 * @param $source
 * @param $target
 * @return mixed
 * @throws \GuzzleHttp\Exception\GuzzleException
 */
function remoteTranslate($keywords, $source = 'zh', $target = 'en')
{
    $tr = new \Stichoza\GoogleTranslate\GoogleTranslate();
    $tr->setSource($source);
    $tr->setTarget($target);
    return $tr->translate($keywords);
}

// 自动生成路由的方法
use app\data\logic\RouteBuildLogLogic;
use think\facade\Log;

/**
 * 追加路由
 * @param $routeName string 路由名称中文
 * @param $app_url string  系统路由 index/page/xxxx
 * @param $rewrite_url string 自定义静态路由
 * @param $params  array 是否带参数
 * @param $route_file string 路由文件
 * @return array|false
 */
function buildRoute($routeName, $app_url, $rewrite_url, $params = [], string $route_file = 'app')
{
    if (strpos($app_url, 'index/page') === false) {
        $app_url = '/index/page/' . $app_url;
    }
    if ($rewrite_url[0] === '/') {//如果第一个字符【存在】斜杠则【去掉】
        $rewrite_url = substr($rewrite_url, 1);
    }

    $directory = root_path() . 'app/index/route';
    $filename = $route_file . '.php';
    $content = "\n" . 'Route::get(\'' . $rewrite_url . '\',\'' . $app_url . '\')';
    if (count($params) > 0) {
        $content .= '->append([';

        foreach ($params as $key => $value) {
            $content .= "'$key'=>$value,";
        }
        $content .= '])';
    }
    $content .= '->name(\'' . $routeName . ",time:" . date('Y-m-d') . '\')';
    $content .= ";";
    $filePath = $directory . '/' . $filename;
    $result = file_put_contents($filePath, $content, FILE_APPEND);
    if ($result) {
        // 写入数据库
        $routeBuildLogLogic = new RouteBuildLogLogic();
        return $routeBuildLogLogic->createNewRouteBuildLog(
            [
                'name' => $routeName,
                'rewrite_url' => $rewrite_url
            ]
        );
    } else {
        return false;
    }
}

/**
 * 删除路由
 * @param $rewrite_url string 指定的路由名称
 * @return boolean
 */
function removeRoute(mixed $rewrite_url, string $route_file = 'app'): bool
{
    if (!$rewrite_url) {
        return true;
    }
    $directory = root_path() . 'app/index/route';
    $filename = $route_file . '.php';
    $filePath = $directory . '/' . $filename;

    $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $newLines = [];
    $found = false;

    foreach ($lines as $line) {
        if (strpos($line, "Route::get('$rewrite_url'") !== false) {
            $found = true;
            continue;
        }
        $newLines[] = $line;
    }

    if ($found) {
        file_put_contents($filePath, implode(PHP_EOL, $newLines));
    }
    return true;
}

/**
 * 更新路由
 * @param $routeName string 路由名称
 * @param $app_url string 原始路由
 * @param $rewrite_url string 自定义路由
 * @param $removeUrl string 要移除的自定义路由
 * @param $params array 是否带餐书
 * @param $route_file string 路由文件
 * @return void
 */
function updateRoute($routeName, $app_url, $rewrite_url, $removeUrl, $params = [], string $route_file = 'app')
{   if(!empty($removeUrl)) {
        if (removeRoute($removeUrl, $route_file)) {
            buildRoute($routeName, $app_url, $rewrite_url, $params, $route_file);
        }
    }
}

/**
 * 调试日志
 * @param $msg
 * @return void
 */
function logDebug($msg)
{
    Log::debug(json_encode($msg, 8));
}

/**
 * 错误记录
 * @param Exception $e
 * @return void
 */
function logError(Exception $e)
{
    Log::error($e->getMessage() . "\n" . $e->getFile() . ":" . $e->getLine());
}